package com.renit.gallery.datasouce

import android.content.Context
import android.util.Log
import androidx.paging.PageKeyedDataSource
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.renit.gallery.PhotoItem
import com.renit.gallery.Pixabay
import com.renit.gallery.TAG
import com.renit.gallery.utils.VolleySinleton

class PixabayDataSource(private val context: Context): PageKeyedDataSource<Int, PhotoItem>() {

    private val queryKey = arrayOf("cat", "dog", "car", "beauty", "phone", "computer", "flower", "animal").random()

    /**
     * 第一次加载
     */
    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, PhotoItem>
    ) {
        val url = "https://pixabay.com/api/?key=27983223-af2a9200de387dcf80b9d1bd4&q=${queryKey}&per_page=50&page=1"

        StringRequest(
            Request.Method.GET,
            url,
            Response.Listener {
                val toList = Gson().fromJson(it, Pixabay::class.java).hits.toList()
                callback.onResult(toList, null, 2)
            },
            Response.ErrorListener {
                Log.e(TAG, "loadInitial: $it")
            }
        ).also {
            VolleySinleton.getInstance(context).requestQueue.add(it)
        }
    }

    /**
     * 加载上一页
     */
    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, PhotoItem>) {
    }

    /**
     * 加载下一页
     */
    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, PhotoItem>) {
        val url = "https://pixabay.com/api/?key=27983223-af2a9200de387dcf80b9d1bd4&q=${queryKey}&per_page=50&page=${params.key}"
        StringRequest(
            Request.Method.GET,
            url,
            Response.Listener {
                val toList = Gson().fromJson(it, Pixabay::class.java).hits.toList()
                callback.onResult(toList, params.key + 1)
            },
            Response.ErrorListener {
                Log.e(TAG, "loadInitial: $it")
            }
        ).also {
            VolleySinleton.getInstance(context).requestQueue.add(it)
        }
    }
}